<script setup lang="ts">
  import { ref } from "vue";
  import { Filter } from "@/components/SideBar";
  import Dialog from "@/components/sql/Dialog.vue";
  // import { AwesomeQR } from "awesome-qr";
  import JSZip from "jszip";
  let searchTime: [number, number] | undefined = undefined;
  const
    fd: RequiredKey<gt.components.SideBar.Filter, "opt">[] = [
      {
        value: "新增", type: "button", opt: {
          async onClick() {
            click(0, format.def.prizeGroup);
          }, type: "primary", class: "mac-ico-add-round"
        },
      },
      {
        label: "生成时间", value: [], type: "datePicker", opt: {
          type: "datetimerange", startPlaceholder: "起始时间", endPlaceholder: "结束时间", clearable: true, onChange(e: [Date, Date] | null) {
            searchTime = e ? [parseInt(e[0].getTime() / 1000), parseInt(e[1].getTime() / 1000)] : undefined;
            init();
          }
        }
      },
      {
        value: "生成二维码", type: "button", opt: {
          type: "danger", async onClick() {
            const domain = await gd.setting.getById("domain") as gt.sql.setting;
            ElMessageBox({
              title: "生成二维码",
              message: `当前将生成(${page.value.total})个二维码,是否继续?`,
              type: "warning",
              callback() { },
              async beforeClose(action, _instance, done) {
                msg("暂停使用二维码生成");
                done();
                return;
                const loading = ElLoading.service({ text: "正在生成,请稍后..." });
                if (action == "confirm") {
                  const r: string[] = await api.request({ "#rule": [{ field: "createTime", logic: "between", value: searchTime }] }, "prizeGroup/ids");
                  const zip = new JSZip();
                  await Promise.all(r.map(async (e) => {
                    const buffer = (await new AwesomeQR({ text: `http://${domain.value}/mp?path=/pages3/lottery?id=${e}` }).draw()) as string;
                    zip.file(e + ".png", buffer.substring(22), { base64: true });
                  }));
                  zip.generateAsync({ type: "blob" }).then((content) => {
                    const a = document.createElement("a");
                    a.download = "奖品二维码.zip";
                    a.href = URL.createObjectURL(content);
                    a.click();
                    URL.revokeObjectURL(a.href);
                    a.remove();
                  });
                }
                loading.close();
                done();
              },
            });
          }, disabled: true
        }
      }
    ],
    page = ref<gt.PageData<gt.sql.prizeGroup>>({ current: 1, size: 10, total: 0, data: [] }),
    filterData = ref<any>(fd),
    tip = ref([
      { label: "复制添加奖品", value: 0, cls: "mac-ico-add-round", per: api.me.per("奖品链接创建") },
      { label: "编辑奖品", value: 1, cls: "mac-ico-edit", per: api.me.per("奖品链接修改") },
      { label: "查看奖品", value: 2, cls: "mac-ico-search", per: true },
      { label: "删除奖品", value: 3, cls: "mac-ico-delete", per: api.me.per("奖品链接删除") },
    ] as const),
    dig = ref({} as InstanceType<typeof Dialog>),
    refreshFilter = ref(0)
    ;
  async function click(method: number, p: gt.sql.prizeGroup) {
    switch (method) {
      case 0: // 新增
        p.id = "";
        break;
      case 1: // 修改
        break;
      case 2: // 查看
        break;
      case 3: // 删除
        break;

      default:
        return;
    }
    await dig.value.open("prizeGroup", method, p, "奖品二维码");
    init();
  }

  async function init() {
    const loading = ElLoading.service({ text: "正在读取数据,请稍后..." }),
      rule: QueryPage<gt.sql.prizeGroup> = {
        "#page": { current: page.value.current, size: page.value.size },
        "#rule": [],
        "#order": [["createTime", "DESC"]]
      };
    fd[2].opt.disabled = !searchTime;
    fd[0].opt.disabled = !api.me.per("奖品链接创建");
    if (searchTime) {
      rule["#rule"]?.push({ field: "createTime", logic: "between", value: searchTime });
    }
    const res = await gd.prizeGroup.read(rule);
    page.value = res;
    refreshFilter.value ^= 1;
    loading.close();
  }
  init();
</script>
<template>
  <div class="prize whf oh y">
    <Filter :data="filterData" isRow class="mb1em" :key="refreshFilter" />
    <el-table stripe highlight-current-row :data="page.data" class="wf fg1" type="expand" row-key="id">
      <el-table-column prop="id" label="id" width="100" show-overflow-tooltip />
      <el-table-column prop="_createTime" label="创建时间" show-overflow-tooltip width="120" />
      <el-table-column prop="name" label="名称" show-overflow-tooltip width="120" />
      <el-table-column prop="image" label="图片" show-overflow-tooltip className="columnimg" width="80">
        <template #default="{ row }">
          <img :src="row.image" v-if="row.image" />
        </template>
      </el-table-column>
      <el-table-column prop="bgColor" label="背景颜色" show-overflow-tooltip width="80">
        <template #default="{ row }">
          <div v-if="row.bgColor" class="whf" :style="{ backgroundColor: row.bgColor }" />
          <div v-else>默认</div>
        </template>
      </el-table-column>
      <el-table-column prop="nameColor" label="名称颜色" show-overflow-tooltip width="80">
        <template #default="{ row }">
          <div v-if="row.nameColor" class="whf" :style="{ backgroundColor: row.nameColor }" />
          <div v-else>默认</div>
        </template>
      </el-table-column>
      <el-table-column prop="sum" label="数量" show-overflow-tooltip width="80" />
      <el-table-column prop="weight" label="权重" show-overflow-tooltip width="80" />
      <el-table-column prop="_v" label="内容" show-overflow-tooltip />
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <div class="buttons x zb">
            <template v-for="a in tip">
              <el-tooltip v-if="a.per" :content="a.label">
                <div :class="a.cls" @click.stop="click(a.value, row)" />
              </el-tooltip>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next, jumper, ->, sizes, total"
      :page-sizes="[10, 20, 30, 40, 50, 100]" v-model:page-size="page.size" :total="page.total"
      v-model:currentPage="page.current" @size-change="init" @current-change="init" />
    <Dialog ref="dig" />
  </div>
</template>
<style lang="scss" scoped>
  .prize {
    position: relative;
    :deep(.columnimg) {
      padding: 0;
      >div {
        >img {
          max-height: 2.86em;
        }
      }
    }
    .whf {
      min-height: 1em;
    }
    .buttons {
      >div {
        cursor: pointer;
        padding: 0 0.4em;
        font-weight: 600;
        &:hover {
          border: 1px solid #a5a5a5;
          box-sizing: border-box;
          border-radius: 0.5em;
          box-shadow: 0 0 10px #000;
        }
      }
      >.mac-ico-add-round, >.mac-ico-people-list {
        color: var(--color-success);
      }
      >.mac-ico-edit, >.mac-ico-warning {
        color: var(--color-warning);
      }
      >.mac-ico-search {
        color: var(--color-primary);
      }
      >.mac-ico-delete, >.mac-ico-my {
        color: var(--color-error);
      }
    }
    .el-table {

      .blueRow {
        color: blue;
      }
      .redRow {
        color: red;
      }
    }
  }
</style>